/**
 * 
 */
package components.IOBuffer;

import java.util.Arrays;

import components.exceptions.InputBufferExceedException;

/***
 * 
 * A buffer receive the input from {@link gui.MyInput}
 * 
 * @author Chz
 * 
 */
public class InputBuffer extends IOBuffer {

	int[] buffer;
	private int startBit = 0, endBit = 0;

	public InputBuffer() {
		buffer = new int[BUFFERLEN];
	}

	/***
	 * Put c into buffer. If the content in the buffer exceeded
	 * {@link InputBuffer.BUFFERLEN},
	 * 
	 * @param i
	 */
	public void putIntoBuffer(int i) {

		buffer[endBit] = i;

		endBit = (endBit + 1) % BUFFERLEN;
	}

	/***
	 * flush out the ASCII form content inside buffer, maximum 16 bits each
	 * time.
	 * 
	 * @return
	 */
	public int[] flush() {

		// temporary hold result, maximum 16 bits.
		int[] ret = new int[16];

		// if the content in buffer is less than 16 bits, then first calculate
		// how many 0s do we need to add into the front of the ret array.
		int tmp = (startBit + 16) % BUFFERLEN;
		int i = 0;
		if (tmp > endBit) {
			tmp = tmp - endBit;

			for (i = 0; i < tmp; i++)
				ret[i] = 0;
		}

		// after filled all the 0s, filled the number.
		for (; i < 16; startBit++, i++) {
			ret[i] = buffer[startBit];
		}

		// at last, startBit shouldn't bigger than endBit, maybe equal.
		return ret;
	}

//	public static void main(String[] args) {
//		InputBuffer ib = new InputBuffer();
//		for (int i = 0; i < 20; i++)
//			ib.putIntoBuffer((char) i);
//		System.out.println(Arrays.toString(ib.flush()));
//		System.out.println(Arrays.toString(ib.flush()));
//
//		System.out.println(ib.startBit);
//		System.out.println(ib.endBit);
//		System.out.println(Arrays.toString(ib.buffer));
//
//	}
}
